import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { pushCancelToken } from './interruptRequest'

import project from '../../project-which'
const { api } = project

function TOKEN() {
  return localStorage[localStorage.tokenName + '_token'] || ''
}

// axios.defaults.baseURL = ''

// 全局拦截器
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.cancelToken = new axios.CancelToken(cancel => {
      pushCancelToken(config.url as string, cancel)
    })

    // 绑定真实API
    if (TOKEN()) {
      config.headers.Authorization = 'Bearer ' + TOKEN()
    }
    // 绑定真实API
    config.url = Reflect.get(api, config.url!) || config.url
    return config
  },
  (err: any) => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  (res: AxiosResponse) => {
    const result = res.data || res
    // .... 可以在这里设置token过期后的操作
    return result
  },
  (err: any) => {
    return Promise.reject(err)
  }
)
